import { game } from "cc";
import { losChannelWeb } from "./losChannelWeb";
import loskc from "./loskc";


export class losChannelKs2 extends losChannelWeb {
    channel: string = 'ks2';
    paraMap: Map<String, string> = new Map([
        ['appId', 'ks696932043197720599'],
        ['videoAd', '2300020141_01'],
        ['insertAd', '2300020141_02'],
        // ['bannerAd', '2300020141_03'],
        ['ctrlId', '67bd9224c8946b1700d95cf8'], //策略开头id
    ]);

    channelObj: any = (window as any).ks;


    ruanzhu: string = `著作权人:南京桔柚檬网络科技有限公司\n软著登记号:2019SR0993607`;


    /* 是否同意了隐私政策 */
    hasPrivacy(): boolean {
        return true;
    }

    /** getSystemInfoSync */
    getSysInfo(): any {
        if (!this.sysInfo) {
            this.sysInfo = this.channelObj.getSystemInfoSync();
        }
        loskc.log(this.sysInfo)
        return this.sysInfo;
    }

    exit(): void {
        this.channelObj.exitApplication();
    }

    init(loginCall: () => void) {
        // super.init(loginCall);
        // loskc.log('隐私', this.hasPrivacy());
        const ctrlId = this.getPara('ctrlId');
        if (ctrlId) {
            const reqData = { 'id': ctrlId };
            loskc.jpost('https://ga.gametdd.com/adCtrl/agd/conf', reqData, (err, re) => {
                loginCall && loginCall();
                if (err) {
                    loskc.err(err);
                    return;
                }
                if ('' + re.code !== '0') {
                    loskc.err('返回值错误:' + JSON.stringify(re));
                    return;
                }
                this.ctrl = {}
                this.ctrl[this.channel] = re.data;
                loskc.log('返回', this.ctrl);
            });
            return;
        }
        loginCall && loginCall();

        // this.getSysInfo()
        // 登录
        // this.ksLogin((e: any) => {
        //     loginCall && loginCall();
        // });0
    }

    ksLogin(callback: (e: any) => void = (e) => { if (e) { console.error(e); } }) {
        const me = this;
        this.channelObj.login({
            success(res) {
                if (!res.code) {
                    loskc.err('登录失败！' + res.errMsg);
                    callback(res);
                    return;
                }
                loskc.log('ksLogin', res.code);
                loskc.jpost('https://ga.gamejym.com/fcm/kuaishou/getOpenId', { appId: me.getPara('appId'), code: res.code }, (err: any, resp: any) => {
                    if (err) {
                        loskc.err(err);
                        callback(err);
                        return;
                    }

                    loskc.log('获取openId', resp);
                    if (!resp.open_id) {
                        loskc.err('获取openId失败', resp);
                        callback(resp);
                        return;
                    }
                    me.channelUserId = resp.open_id || '';
                    callback("success");
                });
            },
            fail() {
                callback("fail");
            }
        });
    }

    showVideo(paras: { sucCall: any; failCall: any; endCall: any; posName?: string; adsid?: string }): void {
        const id = this.getPara('videoAd');
        if (!id) {
            paras.sucCall && paras.sucCall();
            return;
        }
        this.rewardedVideoAd = this.channelObj.createRewardedVideoAd({
            adUnitId: id
        });
        if (this.videoFns['onError']) {
            this.rewardedVideoAd.offError(this.videoFns['onError']);
        }
        if (this.videoFns['onClose']) {
            this.rewardedVideoAd.offClose(this.videoFns['onClose']);
        }
        game.pause();
        const me = this;
        me.videoFns['onError'] = (err) => {
            loskc.err(err);
            game.resume();
            paras.failCall();
            paras.endCall();
            loskc.log('onError');
        }
        let watchTime = 0;
        me.videoFns['onClose'] = (res) => {
            game.resume();
            let reportTime = (Date.now() - watchTime) / 1000
            loskc.log("广告观看时长： " + reportTime)
            if (res && res.isEnded) {
                // 正常播放结束，可以下发游戏奖励
                paras.sucCall();
                loskc.eventReport('广告完成-' + paras.posName);
            } else {
                paras.failCall();
            }
            paras.endCall();
            loskc.log('onClose');
        };
        me.rewardedVideoAd.onError(me.videoFns['onError']);
        me.rewardedVideoAd.onClose(me.videoFns['onClose']);
        me.rewardedVideoAd.show()
            .then(() => {
                loskc.log('激励视频 广告显示');
                watchTime = Date.now()
            }).catch((err) => {
                me.rewardedVideoAd.show()
                    .then(() => {
                        watchTime = Date.now()
                    }).catch((err) => {
                        game.resume();
                    });
            });
    }
    showInter(isForce?: boolean): void {
        const id = this.getPara('insertAd');
        if (!id) {
            return;
        }

        loskc.log('showInter isShow', id);
        this.interstitialAd = this.channelObj.createInterstitialAd({
            adUnitId: id,
        });
        this.interstitialAd.onError(res => {
            loskc.err(res)
        });
        this.interstitialAd.onClose(res => {
            //插屏广告关闭事件  
            loskc.log('插屏广告关闭事件', res)
        })
        const p3 = this.getCtrl('p3')
        loskc.log('p3，延迟弹出插屏,当前值：' + p3)
        setTimeout(() => {
            this.interstitialAd.show()
                .then((result) => {
                    loskc.log('插屏广告展示完成', result);
                }).catch((err) => {
                    loskc.err('插屏广告展示失败', err);
                });
        }, p3 * 1000);
    }
    showBanner(isForce?: boolean, styleFn?: any, where?: string): void {
        const id = this.getPara('bannerAd');
        if (!id) {
            return;
        }
        const p1 = (this.ctrl && this.ctrl.p1) ? (parseInt(this.ctrl.p1)) : 0;
        loskc.log("p1 ==> 控制banner是否展示，值0为不展示，1为展示 ： " + p1)
        if (!p1 && !isForce) {
            loskc.log('广告策略p1不展示banner');
            return;
        }
        loskc.log('showBanner', id);
        this.bannerAd = this.channelObj.createBannerAd({
            posId: id,
            adIntervals: 30, // 自动刷新频率不能小于30秒
            // style: {
            //     left: 0,
            //     // top: windowHeight - 300,
            // },
        });
        this.bannerAd.onError(err => {
            loskc.log('banner广告加载失败' + JSON.stringify(err));
        });

        this.bannerAd.show().then(() => {
            loskc.log('banner广告展示完成');
        }).catch((err) => {
            loskc.log('banner广告展示失败' + JSON.stringify(err));
        });
    }

    closeBanner(): void {
        if (this.bannerAd) {
            this.bannerAd.hide();
            this.bannerAd.destroy()
        }
    }


    private bannerTimeId = -1;
    showBannerByTime(isForce: boolean = false) {
        let t = 30;
        const p4 = this.getCtrl('p4');
        if (p4 < 1) {
            loskc.log('banner不展示');
            return;
        }
        if (this.bannerTimeId >= 0) {
            clearInterval(this.bannerTimeId);
        }
        this.closeBanner();
        if (t < 30) {
            t = 30;
        }
        this.showBanner(isForce, null, 'battle');
        this.bannerTimeId = setInterval(() => {
            this.showBanner(isForce, null, 'battle');
        }, t * 1000);
    }

    closeBannerByTime() {
        if (this.bannerTimeId >= 0) {
            clearInterval(this.bannerTimeId);
        }
        this.closeBanner();
    }

    needShowPrivacy(): boolean {
        return false
    }
    canSupportAddShortcut(): boolean {
        return true
    }
    canSupportCommonUse(): boolean {
        return true;
    }
    canSupportSideBar(): boolean {
        return false
    }
    /** 是否支持分享 */
    canShare(): boolean {
        return false;
    }
    doAction(type: number, channelNames: string[], stateCallFunc?: (enabled: boolean, val: number) => void) {
        let canExe = false;
        if (channelNames) {
            channelNames.forEach(channelName => {
                if (channelName == this.channel) {
                    canExe = true;
                }
            })
        }
        if (!canExe)
            return;
        loskc.log("☆☆☆☆☆☆☆ 调用doAction，策略：" + type)
        switch (type) {
            case 1:
                {
                    const p1 = this.getCtrl('p1')
                    loskc.log("补充体力、体力特权这两个界面加文字“观看视频免费领取”，勾选状态下隐藏放弃按钮，不勾选则显示。0为不勾选状态，1为勾选状态 " + p1)
                    stateCallFunc && stateCallFunc(p1 != 0, p1)
                }
                break;
            case 2:
                {
                    const p2 = this.getCtrl('p2')
                    loskc.log("二级界面弹出插屏，开关由p2控制，0为关闭，1为打开，延迟时间由p3控制  " + p2)
                    stateCallFunc && stateCallFunc(p2 != 0, p2)
                    this.showInter()
                }
                break;
            case 4:
                {
                    const p4 = this.getCtrl('p4')
                    loskc.log("玩家每次登录游戏及返回主页弹出登录奖励，领取之后则不弹，每天可领取。奖励内容为10点体力  " + p4)
                    stateCallFunc && stateCallFunc(p4 != 0, p4)
                }
                break;
            case 5:
                {
                    const p5 = this.getCtrl('p5')
                    loskc.log("等级提升之后弹出九宫格，0为关闭，1为打开  " + p5)
                    stateCallFunc && stateCallFunc(p5 != 0, p5)
                }
                break;
            case 7:
                {
                    const p7 = this.getCtrl('p7')
                    loskc.log("挑战模式成功，胜利后点击“下一关”弹出九宫格，0为关闭，1为打开  " + p7)
                    stateCallFunc && stateCallFunc(p7 != 0, p7)
                }
                break;
            default:
                {
                    let getVal = 'p' + type
                    let _switch = this.getCtrl(getVal);
                    loskc.log("当前开关：" + getVal + ", 当前值：" + _switch)
                    stateCallFunc && stateCallFunc(_switch != 0, _switch)
                }
                break;
        }
    }
    addShortcut(paras: { sucCall: any, failCall: any }): void {
        this.channelObj.addShortcut({
            success() {
                console.log("添加桌面成功");
            },
            fail(err) {
                if (err.code === -10005) {
                    console.log("暂不支持该功能");
                } else {
                    console.log("添加桌面失败", err.msg);
                }
            },
        });
    }
    addCommonUse(paras: { sucCall: any, failCall: any }): void {
        this.channelObj.addCommonUse({
            success() {
                console.log("设为常用成功");
            },
            fail(err) {
                if (err.code === -10005) {
                    console.log("暂不支持该功能");
                } else {
                    console.log("设为常用失败", err.msg);
                }
            },
        });
    }
}